//
//  GYRegisterViewController.m
//  GoodLuck
//
//  Created by apple on 2018/1/30.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYRegisterViewController.h"
#import "GYCitySelectViewController.h"
#import "GYButton.h"
#import "GYNetWorkTools.h"
#import "GYUserAgreementViewController.h"

@interface GYRegisterViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *bgView;

@property (weak, nonatomic) IBOutlet UIButton *registerBtu;

@property (weak, nonatomic) IBOutlet UITextField *UNTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *PWTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *conformPwTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextFiled;

@property (weak, nonatomic) IBOutlet UITextField *SMSTextFiled;
@property (weak, nonatomic) IBOutlet UIButton *SMSBtu;
@property (weak, nonatomic) IBOutlet UIButton *cityBtu;

/** 省份ID */
@property (nonatomic, strong) NSString *provice_id;

/** 城市ID */
@property (nonatomic, strong) NSString *city_id;

/** 地区ID */
@property (nonatomic, strong) NSString *area_id;

/** 记时定时器 */
@property (nonatomic, strong) dispatch_source_t timer;

@end

@implementation GYRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化
    [self setupUI];
}

- (void)setupUI {
    self.navigationItem.title = @"会员注册";
    self.registerBtu.layer.cornerRadius = 4;
    //给按钮文字设置下划线
//    NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:@"点击获取短信"];
//    NSRange titleRange = {0,[title length]};
//    [title addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:titleRange];
//    [self.SMSBtu setAttributedTitle:title
//                          forState:UIControlStateNormal];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"arrow_left_b" tagret:self action:@selector(leftBtuClick) button:nil];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"登入" style:UIBarButtonItemStylePlain target:self action:@selector(loginBtuClick)];
    
    //添加同意按钮
    GYButton *btu = [GYButton buttonWithType:GYButtonTypeHorizontalImageTitle];
    [btu setImage:[UIImage imageNamed:@"weixuanzhong"] forState:GYControlStateNormal];
    [btu setTitle:@"同意" forState:GYControlStateNormal];
    [btu setImage:[UIImage imageNamed:@"xuanzhong"] forState:GYControlStateSelected];
    btu.imageSize = CGSizeMake(15, 15);
    btu.selected = YES;
    btu.fontSize = 14;
    btu.frame = CGRectMake(20, self.registerBtu.y-45, 60, 30);
    [btu addTarget:self action:@selector(agreeBtuClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.bgView addSubview:btu];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.view endEditing:YES];
}


#pragma mark -- 按钮点击事件

- (void)leftBtuClick {
    [self.navigationController popViewControllerAnimated:YES];
//    //1.显示底部工具栏
//    self.tabBarController.tabBar.hidden = NO;
//
//    //2.回到主界面
//    self.tabBarController.selectedIndex = 0;
    
    //[self dismissViewControllerAnimated:YES completion:nil];
}

//是否同意协议
- (void)agreeBtuClick:(GYButton *)sender {
    sender.selected = !sender.selected;
    
    //如果不同意协议 ,则不能注册
    if (!sender.selected) {
        self.registerBtu.enabled = NO;
        [self.registerBtu setBackgroundColor:RGBColor(238, 238, 238)];
        self.registerBtu.titleLabel.textColor = RGBColor(85, 85, 85);
    }else {
        self.registerBtu.enabled = YES;
        [self.registerBtu setBackgroundColor:RGBColor(68, 165, 25)];
        self.registerBtu.titleLabel.textColor = [UIColor whiteColor];
    }
}

//用户协议按钮点击事件
- (IBAction)UserAgreementBtuClick {
    GYUserAgreementViewController *userAgreeMentVC = [[GYUserAgreementViewController alloc] initWithNibName:@"GYUserAgreementViewController" bundle:nil];
    [self.navigationController pushViewController:userAgreeMentVC animated:YES];
}

- (IBAction)getSMSCodeMessage:(UIButton *)sender {
    
    //1.首先判断手机号
    if ([self isMobileNumber:self.phoneTextFiled.text] && self.phoneTextFiled.text.length != 0) {
        //2.发送验证码
        [GYNetWorkTools requestSMSCode:self.phoneTextFiled.text success:^(NSDictionary *obj) {
            //NSLog(@"obj=======%@",obj);
            NSString *code = [obj objectForKey:@"code"];
            if ([code intValue] == 200) {
                [EasyTextView showText:@"验证码发送成功!"];
                //2.1.创建GCD定时器
                //NSDictionary *datas = [obj objectForKey:@"datas"];
                __block int count = 60;//[[datas objectForKey:@"sms_time"] intValue];
                sender.enabled = NO;
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
                
                self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
                dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
                dispatch_source_set_event_handler(self.timer, ^{
                    //2.2改变按钮文字
                    count = count - 1;
                    if (count <= 0) {
                        self.timer = nil;
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [sender setTitle:@"点击获取短信" forState:UIControlStateNormal];
                            sender.enabled = YES;
                        });
                    }else {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [sender setTitle:[NSString stringWithFormat:@"%d秒",count] forState:UIControlStateNormal];
                        });
                    }
                });
                dispatch_resume(self.timer);
            }else {
                NSDictionary *datas = [obj objectForKey:@"datas"];
                [EasyTextView showText:[datas objectForKey:@"error"]];
                NSLog(@"获取验证码失败===%@",[datas objectForKey:@"error"]);

            }
        } error:^(NSError *error) {
            [EasyTextView showText:@"验证码获取失败,请检查网络!"];
           NSLog(@"获取验证码失败===%@",error);
        }];
    }
}


//登入
//- (void)loginBtuClick {
//    [self.navigationController popViewControllerAnimated:YES];
//}

- (IBAction)citySelectBtuClick:(UIButton *)sender {
    
    if (![self.conformPwTextFiled.text isEqualToString:self.PWTextFiled.text]) {
        [EasyTextView showText:@"两次输入密码不一致!"];
        return;
    }
    
    GYCitySelectViewController *citySelectVC = [[GYCitySelectViewController alloc] initWithNibName:@"GYCitySelectViewController" bundle:nil];
    citySelectVC.block = ^(NSString *address, NSString *province_id, NSString *city_id, NSString *area_id) {
        [sender setTitle:address forState:UIControlStateNormal];
        self.provice_id = province_id;
        self.city_id = city_id;
        self.area_id = area_id;
    };
    [self.navigationController pushViewController:citySelectVC animated:YES];

}

- (IBAction)registerBtuClick:(UIButton *)sender {
    
    NSString *text = [self.cityBtu currentTitle];
    NSString *userName = self.UNTextFiled.text;
    //判断信息是否填写完全
    if (!(userName.length >= 6 && userName.length <= 20)) {
        [EasyTextView showText:@"输入的用户名格式不正确!"];
        NSLog(@"请输入正确的用户名...");
        return;
    }
    
    NSString *pwd = self.PWTextFiled.text;
    if (![self judgePassWordLegal:pwd]) {
        [EasyTextView showText:@"请输入6-20位密码，由数字和字母组成!"];
        NSLog(@"请输入6-20位密码");
        return;
    }
    
    if (![self.conformPwTextFiled.text isEqualToString:pwd]) {
        [EasyTextView showText:@"两次输入密码不一致!"];
        NSLog(@"输入密码与确认密码不一致...");
        return;
    }
    
    if (text.length == 0) {
        [EasyTextView showText:@"请选择地址!"];
        NSLog(@"请选择地区...");
        return;
    }
    
    if (self.phoneTextFiled.text.length == 0) {
        [EasyTextView showText:@"请输入正确的手机号!"];
        NSLog(@"请输入手机号...");
        return;
    }
    
    if (self.SMSTextFiled.text.length == 0) {
        [EasyTextView showText:@"请输入短信验证码!"];
        NSLog(@"请输入验证码...");
        return;
    }
    
    //发送注册请求
    [GYNetWorkTools requestUserRegister:self.UNTextFiled.text password:self.PWTextFiled.text password_confirm:self.conformPwTextFiled.text province_id:self.provice_id city_id:self.city_id area_id:self.area_id phone:self.phoneTextFiled.text area_info:text sms_code:self.SMSTextFiled.text inviter_code:@"0" success:^(NSDictionary *obj) {
        //NSLog(@"obj ==== %@",obj);
        NSString *code = [obj objectForKey:@"code"];
        if ([code intValue] == 200) {
            [EasyTextView showSuccessText:@"注册成功!"];
            //注册成功之后 调转到登陆界面
            [self leftBtuClick];
        }else {
            NSDictionary *datas = [obj objectForKey:@"datas"];
            [EasyTextView showText:[NSString stringWithFormat:@"注册失败,%@",[datas objectForKey:@"error"]]];
            NSLog(@"网络加载数据出错%@",[datas objectForKey:@"error"]);
        }
    } error:^(NSError *error) {
        [EasyTextView showText:@"注册失败!"];
        NSLog(@"registerUesrFailed===%@",error);
    }];
}

#pragma mark -- UITextFileDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (textField == self.PWTextFiled) {
        if (!(self.UNTextFiled.text.length >= 6 && self.UNTextFiled.text.length <= 20)) {
            [EasyTextView showText:@"输入的用户名格式不正确!"];
            [textField resignFirstResponder];
        }
    }else if (textField == self.conformPwTextFiled) {
        if (![self judgePassWordLegal:self.PWTextFiled.text]) {
            [EasyTextView showText:@"请输入6-20位密码，由数字和字母组成!"];
            [textField resignFirstResponder];
        }
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

/*
 判断用户输入的密码是否符合规范，符合规范的密码要求：
 1. 长度大于6位
 2. 密码中必须同时包含数字和字母
 */
- (BOOL)judgePassWordLegal:(NSString *)pass{
    BOOL result = false;
    if ([pass length] >= 6){
        // 判断长度大于8位后再接着判断是否同时包含数字和字符
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:pass];
    }
    return result;
}

#pragma mark--判断手机号码
- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    //    电信号段:133/153/180/181/189/177
    //    联通号段:130/131/132/155/156/185/186/145/176
    //    移动号段:134/135/136/137/138/139/150/151/152/157/158/159/182/183/184/187/188/147/178
    //    虚拟运营商:170
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    //     NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    NSString * CM = @" ^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    //     NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    NSString * CU =  @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    //     NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    NSString * CT = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

@end
